<template>
    <div class="page-main">
        <div class="header-container">
            <router-link to="/MyInfo" class="back-button">
                <img src="@/assets/images/mine/back.png" alt="返回图标" class="return-image" />
            </router-link>
            <p>文章历史记录</p>
            <!-- 清空按钮 -->
            <div class="clear-btn" @click="clearHistory">
                <img src="@/assets/images/home/delete.png" alt="清空图标" class="clear-image" />
            </div>
        </div>
        <div class="content-container">
            <div v-if="!cardList.length" class="empty-state">
                <img src="@/assets/images/home/norecord.png" alt="没有记录图标" class="empty-image">
                <p class="empty-text">未曾留下足迹，期待您的浏览</p>
            </div>
            <template v-else>
                <div class="date-selector">
                    <div 
                        v-for="(label, index) in dateLabels" 
                        :key="index" 
                        :class="['date-tab', activeTab === label ? 'active' : '']"
                        @click="activeTab = label"
                    >
                        {{ label }}
                    </div>
                </div>
                <template v-for="(group, date) in filteredCards" :key="date">
                    <div class="date-divider">
                        <span class="date-text">{{ date }}</span>
                        <span class="divider-line"></span>
                    </div>
                    <div class="waterfall-container">
                        <div class="waterfall-column" v-for="(column, index) in group" :key="index">
                            <div v-for="card in column" :key="card.essayId" class="card-item" @click="goToDetail(card.essayId)">
                                <div class="card-img">
                                    <img :src="card.coverImg" alt="文章图片" />
                                </div>
                                <div class="card-content">
                                    <h3 class="title">{{ card.title }}</h3>
                                    <p class="content">{{ card.content }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getHistoryAPI, clearHistoryAPI } from '../api/index';
import { showToast } from 'vant';

const router = useRouter();
const cardList = ref([]);
const dateLabels = ['今天', '昨天', '更早'];
const activeTab = ref('今天');

// 格式化日期
const formatDate = (date) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const targetDate = new Date(date);
    targetDate.setHours(0, 0, 0, 0);

    const diffTime = Math.abs(today - targetDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return '今天';
    if (diffDays === 1) return '昨天';
    return '更早';
};

// 按日期分组卡片
const groupedCards = computed(() => {
    const groups = {};

    cardList.value.forEach(card => {
        const dateKey = formatDate(card.accessTime);
        if (!groups[dateKey]) {
            groups[dateKey] = [[], []];
        }

        const columnIndex = groups[dateKey][0].length <= groups[dateKey][1].length ? 0 : 1;
        groups[dateKey][columnIndex].push(card);
    });

    // 按固定顺序排列：今天、昨天、更早
    const orderedKeys = ['今天', '昨天', '更早'];
    return orderedKeys.reduce((acc, key) => {
        if (groups[key]) {
            acc[key] = groups[key];
        }
        return acc;
    }, {});
});

// 根据选中的标签过滤卡片
const filteredCards = computed(() => {
    if (activeTab.value === '全部') {
        return groupedCards.value;
    }
    
    const result = {};
    if (groupedCards.value[activeTab.value]) {
        result[activeTab.value] = groupedCards.value[activeTab.value];
    }
    return result;
});

const getcollectionList = () => {
    getHistoryAPI().then((res) => {
        cardList.value = res.data.data;
    }).catch((error) => {
        showToast('获取文章列表失败，请稍后重试' + error);
    });
};

const clearHistory = () => {
    clearHistoryAPI().then((res) => {
        cardList.value = [];
        showToast('清空成功');
    }).catch((error) => {
        showToast('清空失败，请稍后重试' + error);
    });
};

const goToDetail = (id) => {
    router.push({
        name: 'ArticleContent',
        params: { id }
    });
};

onMounted(() => {
    getcollectionList();
});
</script>

<style lang="scss" scoped>
.page-main {
    background: #f8f9fa;
    min-height: 100vh;
    padding: 60px 0 0;
    font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;

    .header-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 60px;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
        z-index: 1000;
    }

    .back-button {
        position: absolute;
        top: 50%;
        left: 15px;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        text-decoration: none;
        color: #333;
    }

    .clear-image {
        position: absolute;
        top: 50%;
        right: 15px;
        transform: translateY(-50%);
        height: 24px;
        opacity: 0.8;
        transition: opacity 0.2s;
        
        &:active {
            opacity: 1;
        }
    }

    .header-container p {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin: 0;
        text-align: center;
    }

    .content-container {
        padding: 15px 12px;
    }

    .date-selector {
        display: flex;
        background-color: #fff;
        border-radius: 10px;
        padding: 3px;
        margin-bottom: 15px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        
        .date-tab {
            flex: 1;
            text-align: center;
            padding: 8px 0;
            font-size: 14px;
            color: #666;
            border-radius: 8px;
            transition: all 0.3s ease;
            
            &.active {
                background-color: #6366F1;
                color: #fff;
                font-weight: 500;
            }
            
            &:not(.active):active {
                background-color: rgba(99, 102, 241, 0.1);
            }
        }
    }

    .empty-state {
        height: calc(100vh - 280px);
        padding: 40px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        .empty-image {
            width: 120px;
            height: 120px;
            margin-bottom: 16px;
            filter: grayscale(20%);
            opacity: 0.8;
            animation: float 3s ease-in-out infinite;
        }
        
        .empty-text {
            font-size: 16px;
            color: #888;
            text-align: center;
            line-height: 1.6;
            max-width: 80%;
            margin: 0 auto;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }
    }

    .date-divider {
        display: flex;
        align-items: center;
        margin: 20px 0 12px;
        
        .date-text {
            font-size: 15px;
            font-weight: 500;
            color: #666;
            margin-right: 10px;
            flex-shrink: 0;
        }
        
        .divider-line {
            flex-grow: 1;
            height: 1px;
            background: linear-gradient(to right, rgba(0,0,0,0.1), rgba(0,0,0,0.02));
        }
    }

    .waterfall-container {
        display: flex;
        justify-content: space-between;
        gap: 10px;
        padding: 0;

        .waterfall-column {
            width: calc(50% - 5px);
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
    }

    .card-item {
        border-radius: 12px;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        display: flex;
        flex-direction: column;
        overflow: hidden;
        transition: transform 0.2s, box-shadow 0.2s;
        
        &:active {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .card-img {
            height: 120px;
            flex-shrink: 0;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                transition: transform 0.3s;
            }
        }

        .card-content {
            padding: 10px 12px;
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #fff;

            .title {
                font-size: 14px;
                font-weight: 600;
                color: #333;
                margin: 0 0 6px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .content {
                font-size: 12px;
                color: #666;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 1.4;
                margin: 0;
            }
        }
    }
}
</style>    